package com.helen.ui.bottom;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.HomeClassificationListAdapter;
import com.helen.adapter.ProductAdapter;
import com.helen.adapter.SaleAdapter;
import com.helen.entity.ArticleEntity;
import com.helen.entity.HomeClassificationEntity;
import com.helen.entity.IndexEntity;
import com.helen.entity.MarqueeEntity;
import com.helen.entity.ProductEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseFragment;
import com.helen.ui.WebViewActivity;
import com.helen.ui.WebViewH5Activity;
import com.helen.ui.donation.DonationActivity;
import com.helen.ui.help.HelpActivity;
import com.helen.ui.newui.ActiveActivity;
import com.helen.ui.product.ProductActivity;
import com.helen.ui.product.ProductDetailActivity;
import com.helen.ui.recoveryclass.RecoveryCommonActivity;
import com.helen.utils.GlideImageLoader;
import com.helen.utils.JsonUtil;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.StatusBarUtil;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.DividerGridItemDecoration;
import com.helen.widget.MarqueeView;
import com.helen.widget.UniversalDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.cache.converter.SerializableDiskConverter;
import com.zhouyou.http.cache.model.CacheMode;
import com.zhouyou.http.cache.model.CacheResult;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by yang on 2018/4/15.
 */

public class ShoppingFragment extends BaseFragment {
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.srl_footer)
    ClassicsFooter srlFooter;
    @BindView(R.id.nestedScrollView)
    NestedScrollView mNestedScrollView;
    @BindView(R.id.ll_top)
    LinearLayout llTop;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.rv_list_classfy)
    RecyclerView rvListClassfy;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.rv_list_sale)
    RecyclerView rvListSale;
    @BindView(R.id.rv_list_product)
    RecyclerView rvListProduct;

    private List<String> bannerList = new ArrayList<>();

    //    首页回收分类
    private List<HomeClassificationEntity> homeClassificationEntityList = new ArrayList<>();
    private HomeClassificationListAdapter homeClassificationListAdapter;

    private Intent ti = null;


    //    商品列表
    private int page = 1;
    private List<ProductEntity> list = new ArrayList();
    private List<ArticleEntity> articleEntityList = new ArrayList();
    private ProductAdapter productAdapter;
    private SaleAdapter saleAdapter;


    //首页数据模型
    private IndexEntity indexEntity;

    @Override
    protected int attachLayoutRes() {

        return R.layout.fragment_shopping;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), null);
        initRefreshLayout();
        setTopView();
        initHomeClassifiCation();
        initSaleActivity();
//        initProductView();
        indexApi();
        articleListApi();
//        productListApi();
    }

    @Override
    protected void updateViews() {
        MyLog.e("yang", "ShoppingFragment");
    }

    private void initRefreshLayout() {
        refreshLayout.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        MyLog.e("yang", "111111111");
                        page = 1;
                        indexApi();
                        articleListApi();
//                        productListApi();
                        refreshLayout.finishRefresh();
                        refreshLayout.setNoMoreData(false);
                    }
                }, 500);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
//                        productListApi();
                        articleListApi();
                    }
                }, 500);
            }
        });

        //触发自动刷新
//        refreshLayout.autoRefresh();
    }


    private void setTopView() {
        final int height = llTop.getLayoutParams().height;
        MyLog.e("yang", "height==" + height);
        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            // 将透明度声明成局部变量用于判断
            int alpha = 0;
            float scale = 0;

            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                MyLog.e("yang", "scrollY==" + scrollY);
                if (scrollY <= height) {
                    llTop.setVisibility(View.VISIBLE);
                    scale = (float) scrollY / height;
                    alpha = (int) (255 * scale);
                    // 随着滑动距离改变透明度
                    llTop.setBackgroundColor(Color.argb(alpha, 0xFF, 0x7A, 0x00));

                } else {
                    if (alpha < 255) {
                        // 防止频繁重复设置相同的值影响性能
                        alpha = 255;
                        llTop.setBackgroundColor(Color.argb(alpha, 0xFF, 0x7A, 0x00));
                    }
                }
                if (scrollY == 0) {
                    llTop.setVisibility(View.GONE);
                }
            }

        });
    }


    //初始化首页数据
    private void initHomeClassifiCation() {
        String[] homeClassificationName = getResources().getStringArray(R.array.home_classification);
        int[] homeClassificationIcon = new int[]{R.mipmap.home_yf, R.mipmap.home_dzcp, R.mipmap.home_sj, R.mipmap.home_jj, R.mipmap.home_lj,
                R.mipmap.home_axjz, R.mipmap.home_ddzy, R.mipmap.home_xybz, R.mipmap.home_xzbb, R.mipmap.home_cjhd};

        for (int i = 0; i < homeClassificationName.length; i++) {
            HomeClassificationEntity homeClassificationEntity = new HomeClassificationEntity();
            homeClassificationEntity.setName(homeClassificationName[i]);
            homeClassificationEntity.setIcon(homeClassificationIcon[i]);
            homeClassificationEntityList.add(homeClassificationEntity);
        }
        homeClassificationListAdapter = new HomeClassificationListAdapter(R.layout.item_home_classification_list, homeClassificationEntityList);
        rvListClassfy.setLayoutManager(new GridLayoutManager(getActivity(), 5));
        rvListClassfy.setAdapter(homeClassificationListAdapter);

        homeClassificationListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        toRecoveryCommonActivity(1);
                        break;
                    case 1:
                       // toRecoveryCommonActivity(2);

                    case 2:
                       // toRecoveryCommonActivity(3);

                    case 3:
                      //  toRecoveryCommonActivity(4);

                    case 4:
                      //  toRecoveryCommonActivity(5);
                        tipDialog();
                        break;
                    case 5:
                        ti = new Intent(getActivity(), DonationActivity.class);
                        startActivity(ti);
                        break;
                    case 6:
                        ti = new Intent(getActivity(), ProductActivity.class);
                        ti.putExtra("type", "3");
                        startActivity(ti);
                        break;
                    case 7:
                        if (checkLoginState()) {
                            ti = new Intent(getActivity(), HelpActivity.class);
                            startActivity(ti);
                        }
                        break;
                    case 8:
                        ti = new Intent(getActivity(), ProductActivity.class);
                        ti.putExtra("type", "1");
                        startActivity(ti);
                        break;
                    case 9:
                        ti = new Intent(getActivity(), ActiveActivity.class);
//                        ti.putExtra("type", "2");
                        startActivity(ti);
                        break;
                }

            }
        });

    }
    private void tipDialog(){
        new UniversalDialog(getActivity()).builder().setTitle("暂未开放")
//                .setMsg("")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                    }

        }).show();
    }

    //    banner
    private void initBanner(final IndexEntity indexEntity) {
        bannerList.clear();
        if (indexEntity != null && indexEntity.getBanner_list().size() > 0) {
            for (int i = 0; i < indexEntity.getBanner_list().size(); i++) {
                bannerList.add(indexEntity.getBanner_list().get(i).getImg());
            }
        }
        banner.setImages(bannerList)
                .setImageLoader(new GlideImageLoader())
//                .setBannerAnimation(CubeOutTransformer.class)
                .start();

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

//           type     0、html5 1、回收旧衣 2、回收电子产品 3、回收书籍 4、回收家具 5、回收垃圾 6、爱心捐赠 7、商品详情
                int type = indexEntity.getBanner_list().get(position).getType();
                MyLog.e("yang", "type==" + type);
                switch (type) {
                    case 0:
                        ti = new Intent(getActivity(), WebViewActivity.class);
                        ti.putExtra("title", indexEntity.getBanner_list().get(position).getTitle());
                        ti.putExtra("url", indexEntity.getBanner_list().get(position).getValue());
                        startActivity(ti);
                        break;
                    case 1:
                        toRecoveryCommonActivity(1);
                        break;
                    case 2:
                        toRecoveryCommonActivity(2);
                        break;
                    case 3:
                        toRecoveryCommonActivity(3);
                        break;
                    case 4:
                        toRecoveryCommonActivity(4);
                        break;
                    case 5:
                        toRecoveryCommonActivity(5);
                        break;
                    case 6:
                        ti = new Intent(getActivity(), DonationActivity.class);
                        startActivity(ti);
                        break;
                    case 7:
                        ti = new Intent(getActivity(), ProductDetailActivity.class);
                        ti.putExtra("productId", Integer.parseInt(indexEntity.getBanner_list().get(position).getValue()));
                        startActivity(ti);
                        break;

                }
            }
        });

    }

    //    公告
    private void setMarqueeView(IndexEntity indexEntity) {
        final List<MarqueeEntity> marqueeBaseModelList = new ArrayList<>();//公告集合
        if (indexEntity != null && indexEntity.getNotice_list().size() > 0) {
            for (int i = 0; i < indexEntity.getNotice_list().size(); i++) {
                marqueeBaseModelList.add(new MarqueeEntity(indexEntity.getNotice_list().get(i).getTitle(), indexEntity.getNotice_list().get(i).getId()));
            }
        }
        marqueeView.startWithList(marqueeBaseModelList);
        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
//                打开详情页为html5  链接地址为 /home/NoticeDetail?id=编号
                ti = new Intent(getActivity(), WebViewH5Activity.class);
                ti.putExtra("id", marqueeBaseModelList.get(position).getId());
                startActivity(ti);
            }
        });
    }

    //   跳转到回收界面
    private void toRecoveryCommonActivity(int iid) {
        if (checkLoginState()) {
            ti = new Intent(getActivity(), RecoveryCommonActivity.class);
            ti.putExtra("iid", iid);
            startActivity(ti);
        }

    }

    //商品列表
    private void initProductView() {
        productAdapter = new ProductAdapter(R.layout.item_product_list, list);
        productAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvListProduct.setLayoutManager(gridLayoutManager);
        rvListProduct.addItemDecoration(new DividerGridItemDecoration(getActivity(), 6f, R.drawable.shape_recyclerview_divider_decoration_commen));
        rvListProduct.setAdapter(productAdapter);
        rvListProduct.setNestedScrollingEnabled(false);
        rvListProduct.setHasFixedSize(true);
        productAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ProductEntity productEntity = (ProductEntity) adapter.getData().get(position);
                Intent ti = new Intent(getActivity(), ProductDetailActivity.class);
                ti.putExtra("productId", productEntity.getId());
//                ti.putExtra("productEntity", productEntity);
                startActivity(ti);
            }
        });
    }


    //特价活动列表
    private void initSaleActivity() {
        saleAdapter = new SaleAdapter(R.layout.item_sale_list, articleEntityList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        rvListSale.setLayoutManager(gridLayoutManager);
        rvListSale.addItemDecoration(new DividerGridItemDecoration(getActivity(), 1f, R.drawable.shape_recyclerview_divider_decoration_commen));
        rvListSale.setAdapter(saleAdapter);
        rvListSale.setNestedScrollingEnabled(false);
        rvListSale.setHasFixedSize(true);
        saleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArticleEntity articleEntity = (ArticleEntity) adapter.getData().get(position);
                Intent ti = new Intent(mContext, WebViewActivity.class);
                ti.putExtra("title", "详情");
                ti.putExtra("url", Constants.API_JSONAPI_MANAGE_ARTICLE_DETAIL + articleEntity.getId());
                mContext.startActivity(ti);


//                IndexEntity.SaleListBean saleListBean = (IndexEntity.SaleListBean) adapter.getData().get(position);
//                Intent ti = new Intent(getActivity(), ProductDetailActivity.class);
//                ti.putExtra("productId", saleListBean.getId());
//                startActivity(ti);
            }
        });
    }


    //    获取商品列表
    private void productListApi() {
        HttpParams params = new HttpParams();
        params.put("productid", "");
        params.put("type", "0");
        params.put("name", "");
        params.put("classid", "");
        params.put("page", page + "");
        params.put("size", "10");
        EasyHttp.post(Constants.API_JSONAPI_PRODUCTLIST)
//                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
//                .cacheKey(Constants.API_JSONAPI_PRODUCTLIST + "_0")
//                .cacheDiskConverter(new SerializableDiskConverter())
                .params(params)
//                .execute(new SimpleCallBack<CacheResult<String>>() {
                .execute(new SimpleCallBack<String>() {

                    @Override
                    public void onCompleted() {
                        super.onCompleted();

                    }

                    @Override
                    public void onError(ApiException e) {

                        MyLog.d(TAG, "获取商品列表失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
//                    public void onSuccess(CacheResult<String> stringCacheResult) {
                    public void onSuccess(String stringCacheResult) {
//                        String data = PhoneUtils.checkResponseFlag2(getActivity(), stringCacheResult.data, TAG);
                        String data = PhoneUtils.checkResponseFlag2(getActivity(), stringCacheResult, TAG);
                        if (data != null) {
                            list = new Gson().fromJson(data, new TypeToken<List<ProductEntity>>() {
                            }.getType());
                            if (page == 1) {
                                productAdapter.setNewData(list);
                            } else {
                                productAdapter.addData(list);
                                productAdapter.notifyDataSetChanged();
                                if (list.size() == 0) {
                                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                } else {
                                    refreshLayout.finishLoadMore();
                                }

                            }

                        }
                    }
                });

    }

    private void articleListApi() {
        HttpParams params = new HttpParams();
        params.put("page", page + "");
        params.put("size", "10");
        EasyHttp.post(Constants.API_JSONAPI_ARTICLE_LIST)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "首页文章数据失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String stringCacheResult) {
                        MyLog.d("yang", "首页文章==" + stringCacheResult);
                        String data = PhoneUtils.checkResponseFlag2(getActivity(), stringCacheResult, TAG);
                        if (data != null) {
                            articleEntityList = new Gson().fromJson(data, new TypeToken<List<ArticleEntity>>() {
                            }.getType());
                            if (page == 1) {
                                saleAdapter.setNewData(articleEntityList);
                                refreshLayout.finishRefresh();
                            } else {
                                saleAdapter.addData(articleEntityList);
                                saleAdapter.notifyDataSetChanged();
                                rvListSale.scrollToPosition(saleAdapter.getData().size());
                                if (articleEntityList.size() == 0) {
                                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                } else {
                                    refreshLayout.finishLoadMore();
                                }

                            }
                        }

                    }
                });
    }


    private void indexApi() {
        mMProgressDialog.show();
        EasyHttp.post(Constants.API_JSONAPI_INDEX)
                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
                .cacheKey(Constants.API_JSONAPI_INDEX)
                .cacheDiskConverter(new SerializableDiskConverter())
                .execute(new SimpleCallBack<CacheResult<String>>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "首页数据失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(CacheResult<String> stringCacheResult) {
                        MyLog.e("yang", "首页==" + stringCacheResult);
                        int code = JsonUtil.getJsonValuesInt(stringCacheResult.data, "code");
                        String msg = JsonUtil.getJsonValuesString(stringCacheResult.data, "msg");
                        if (code == 0) {
                            Gson gson = new GsonBuilder().create();
                            indexEntity = gson.fromJson(stringCacheResult.data, IndexEntity.class);
                            initBanner(indexEntity);
                            setMarqueeView(indexEntity);
                        } else {
                            MToast.makeTextShort(getActivity(), msg).show();
                        }
                    }
                });
    }


}
